package com.ruanyin.web.servlet;

import com.ruanyin.domain.User;
import com.ruanyin.service.UserService;
import com.ruanyin.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/userAlterServlet")
public class UserAlterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 编码问题
        request.setCharacterEncoding("utf-8");

        // 接收数据
        Map<String, String[]> newUser = request.getParameterMap();
        System.out.println(newUser.values());

        // 封装数据为对象
        User user = new User();
        try {
            BeanUtils.populate(user, newUser);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        // 调用service的alterUser(User newUser)修改数据库
        UserService service = new UserServiceImpl();
        service.alterUser(user);

        // 跳转到list.jsp对应的servlet
        response.sendRedirect(request.getContextPath() + "/userListServlet");
    }
}
